package org.PropertyManageMentSystem.Manager;

import org.PropertyManageMentSystem.Data.EmergencyType;
import org.PropertyManageMentSystem.Data.MysqlConfig;

import java.sql.*;
import java.util.ArrayList;

public class EmergencyTypeManager {
    private Connection conn;

    public EmergencyTypeManager(MysqlConfig config) throws SQLException, ClassNotFoundException {
        try {
            //加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        try {
            //创建连接
            conn = DriverManager.getConnection(config.getUrl(), config.getUser(), config.getPassword());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public ArrayList<EmergencyType> getEmergencyTypeList() throws SQLException {
        String sql="select * from emergencytype";
        PreparedStatement pst=conn.prepareStatement(sql);
        ResultSet rs = pst.executeQuery();
        ArrayList<EmergencyType> emergencyTypes = new ArrayList<>();
        while (rs.next()) {
            EmergencyType emergencyType = new EmergencyType(rs.getLong("typeId"),
                    rs.getString("typename"));
            emergencyTypes.add(emergencyType);
        }
        if (emergencyTypes.isEmpty()) {
            return null;
        }
        else {
            return emergencyTypes;
        }
    }

    public void addEmergencyType(String name) throws SQLException {
        String sql="insert into emergencytype (typename) values (?)";
        PreparedStatement pst=conn.prepareStatement(sql);
        pst.setString(1, name);
        pst.executeUpdate();
    }
}
